package com.User.service.Impl;

import com.User.entity.User;
import com.User.mapper.UserMapper;
import com.User.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.configer.RedisConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.APIRespones;
import com.utils.Utils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private RedisConfig redisConfig = new RedisConfig();
    private Jedis jedis= redisConfig.jedisPool().getResource();

    private BCryptPasswordEncoder passwordEncoder;
    public UserServiceImpl(UserMapper userMapper, BCryptPasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Transactional
    public APIRespones isLogin(String token) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> jsonMap = null;
        try {
            jsonMap = objectMapper.readValue(token, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return APIRespones.failure("JSON解析异常");
        }

        // 获取 "token" 属性的值
        String tokenValue = (String) jsonMap.get("token");

        try {
            Map<String, String> keyValueMap = jedis.hgetAll(tokenValue);
            for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            }
            System.out.println(tokenValue);
            System.out.println(keyValueMap);
            if (!keyValueMap.isEmpty()) {
                return APIRespones.success(Utils.createMap("data", "用户已登录"));
            } else {
                return APIRespones.failure("用户未登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return APIRespones.failure("运行时异常");
        }
    }





    @Override
    public APIRespones register(User user) {
        // 检查邮箱是否已被使用
        User existingUser = userMapper.findByEmail(user.getEmail());
        if (existingUser != null) {
            return APIRespones.failure("邮箱已被使用");
        }

        // 对密码进行加密
        String encodedPassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodedPassword);

        // 注册用户
         userMapper.registerUser(user.getUsername(),user.getPassword(),user.getEmail());

        // 获取单例UserInstance并填充注册后的信息

        Map<String, Object> keyValues = new HashMap<>();
        String accessToken = UUID.randomUUID().toString().replace("-", "");
        return setTokenToRedis(user, keyValues, accessToken,userMapper.lastInsertId());
    }

    private APIRespones setTokenToRedis(User user, Map<String, Object> keyValues, String accessToken,Integer userId) {
        System.out.println("当前token分配："+accessToken);
        keyValues.put("access_token", accessToken);
        keyValues.put("user_id", userId);
        System.out.println(keyValues);
        Map<String, String> keyValuesString = keyValues.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString()));
        jedis.hmset(accessToken, keyValuesString);
        jedis.pexpire(accessToken, 1800000);
        Map<String, String> keyValueMap = jedis.hgetAll(accessToken);
        for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
        return APIRespones.success(keyValues);
    }

    @Override
    @Transactional
    public APIRespones login(String username, String password) {
        User user = userMapper.findByUserame(username);
        System.out.println(username);
        System.out.println(password);
        // 验证用户凭证
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            return APIRespones.failure("无效的凭证（用户名或密码错误）");
        }
        // 登录成功，生成访问令牌并返回
        String accessToken = UUID.randomUUID().toString().replace("-", "");
        Map<String, Object> keyValues = new HashMap<>();
        return setTokenToRedis(user, keyValues, accessToken,user.getId());
    }
    @Override
    @Transactional
    public APIRespones getUserInfo( String token) {
        // 获取 Redis 中的用户 ID
        String userId = jedis.hget(token, "user_id");
        if (userId == null) {
            // 未找到用户 ID，返回错误响应
            return APIRespones.failure("未找到用户 ID");
        }

        // 使用 MyBatis-Plus 查询该用户的信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            // 未找到该用户，返回错误响应
            return APIRespones.failure("未找到该用户");
        } else {
            // 找到了该用户，返回成功响应
            Map<String, Object> keyValues = new HashMap<>();
//            keyValues.put("id", user.getId());
            keyValues.put("username",user.getUsername());
            keyValues.put("nickname", user.getNickname());
            keyValues.put("email", user.getEmail());
            keyValues.put("identity", user.getIdentity());
            keyValues.put("signature",user.getSignature());
            String HeadSculptureUrl = Utils.generateImageUrl(user.getHeadSculpture());

            keyValues.put("HeadSculptureUrl",HeadSculptureUrl);
            return APIRespones.success(keyValues);
        }
    }
    @Override
    @Transactional
    public APIRespones uploadUserHead( MultipartFile file, String token) {
        // 上传头像图片到OSS
        String fileName = null;
        try {
            fileName = Utils.uploadImage(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 根据token获取用户ID
        Integer userId = Utils.getTokenUserId(token);
        if (userId == null) {
            return APIRespones.failure("无效的token");
        }

        // 更新用户的头像字段
        userMapper.updateUserHeadSculpture(userId, fileName);

        // 获取更新后的用户信息
        User user = userMapper.selectById(userId);
        System.out.println(fileName);
        user.setHeadSculptureUrl(fileName);
        // 构建成功响应的数据
        Map<String, Object> data = new HashMap<>();
        data.put("message", "头像上传成功");
        String HeadSculptureUrl = Utils.generateImageUrl(user.getHeadSculpture());

        data.put("headSculptureUrl", HeadSculptureUrl);

        return APIRespones.success(data);
    }
}
